package com.example.hsh.homefragment.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;



/**
 * Created by HSH on 2016/12/13.
 * 此处RecyclerView.Adapter不能再指定泛型:RecyclerView.Adapter<BaseAdapter.BaseHolder>
 *
 */
public abstract class BaseAdapter<T> extends RecyclerView.Adapter{

    protected OnItemClickListener mItemListener;
    protected Context mContext;
    protected LayoutInflater inflater;

    protected ArrayList<T> datas = new ArrayList<>();

    public BaseAdapter(Context context) {
        mContext = context;
        inflater = LayoutInflater.from(context);
    }

    public void addDatas(List<T> datas) {
        this.datas.addAll(datas);
        notifyDataSetChanged();
    }

    public void replaceDatas(List<T> datas) {
        this.datas.clear();
        this.datas.addAll(datas);
        notifyDataSetChanged();
    }

    public List<T> getDatas() {
        return this.datas;
    }

    @Override
    public BaseHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(getItemLayoutRes(), parent, false);
        return new BaseHolder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        onBindView((BaseHolder)holder, datas.get(position), position);
    }

//    @Override
//    public void onBindViewHolder(BaseHolder holder, int position) {
//        onBindView((BaseHolder)holder, datas.get(position), position);
//    }


    @Override
    public int getItemCount() {
        return this.datas.size();
    }

    public abstract int getItemLayoutRes();

    public abstract void onBindView(BaseHolder holder, T bean, int position);
    public void setOnItemClickListener(OnItemClickListener listener) {
        mItemListener = listener;
    }

    public interface OnItemClickListener{
        void onItemClick(View view, int position);
    }

    public class BaseHolder extends RecyclerView.ViewHolder{
        SparseArray<View> views;

        public BaseHolder(View itemView) {
            super(itemView);
            views = new SparseArray<>();

            if (mItemListener != null) {
                itemView.setOnClickListener(v -> mItemListener.onItemClick(v, getLayoutPosition()));
            }
        }

        public <V extends View> V getViewById(int id) {
            View view = views.get(id);
            if (view == null) {
                view = itemView.findViewById(id);
                views.put(id, view);
            }
            return (V) view;
        }

    }
}
